package com.example.block_chain.service.impl.account;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.block_chain.common.AppHttpCodeEnum;
import com.example.block_chain.common.ResponseResult;
import com.example.block_chain.domain.pojo.Student;
import com.example.block_chain.mapper.StudentMapper;
import com.example.block_chain.service.account.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public ResponseResult register(String sNo, String password, String confirmedPassword,
                                   String name,String sID,String sex) {

        if(sNo.isEmpty()){
            return ResponseResult.errorResult(500,"学号不能为空");
        }
        //这里要判断学号是几位数，几位数我忘记了
//        if(sNO.length() > 100){
//            return ResponseResult.errorResult("500");
//        }

//        if(sNO.length() > 100||confirmedPassword.length()>100){
//            return ;
//        }

        if(password.isEmpty()||confirmedPassword.isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if(!password.equals(confirmedPassword)){
            return ResponseResult.errorResult(500,"两次输入的密码不一样");
        }

        if(name.isEmpty()) {
            return ResponseResult.errorResult(500,"身份证号不能为空");
        }

        if(sID.isEmpty()) {
            return ResponseResult.errorResult(500,"身份证号不能为空");
        }
        if(sID.length()!=18) {
            return ResponseResult.errorResult(500,"身份证号格式有误");
        }

        if(sex.isEmpty()) {
            return ResponseResult.errorResult(500,"性别不能为空");
        }


        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("s_no",sNo);
        List<Student> users = studentMapper.selectList(queryWrapper);
        if(!users.isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.USERNAME_EXIST);
        }

        //对原始密码进行编码，暂时用不到
        String encodedPassword = passwordEncoder.encode(password);

        System.out.println("encodedPassword="+encodedPassword);

        String grade = sNo.substring(0, 4);
        String classId = sNo.substring(4, 6);

        Student student = new Student(null,sNo,name,encodedPassword,null,sID,classId,null,null,null,grade,sex);
        studentMapper.insert(student);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
